package com.jingbaoduo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingbaoduo.common.R;
import com.jingbaoduo.domain.Category;
import com.jingbaoduo.domain.Goods;
import com.jingbaoduo.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;




    @GetMapping
    public R<List<Goods>> listAll(String name){
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Goods::getGoodsName,name);
        List<Goods> list = goodsService.list(queryWrapper);
        if (list == null){
            return R.error("查询失败");
        }
        return R.success(list);

    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name, Long categoryId){
        Page<Goods> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Goods::getGoodsName,name);
        queryWrapper.eq(!Objects.isNull(categoryId),Goods::getCategoryId,categoryId);
        queryWrapper.orderByAsc(Goods::getCreateTime);

        goodsService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    @Cacheable(value = "goodsCache", key = "#categoryId")
    @GetMapping("/{categoryId}")
    public R<List<Goods>> list(@PathVariable Long categoryId){
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getCategoryId,categoryId);

        List<Goods> list = goodsService.list(queryWrapper);
        if (list == null){
            return R.error("查询失败");
        }
        return R.success(list);

    }

    @GetMapping("/detail/{goodsId}")
    public R<Goods> detail(@PathVariable Long goodsId){
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getGoodsId,goodsId);
        Goods goods = goodsService.getOne(queryWrapper);

        if (goods == null){
            return R.error("查询失败");
        }
        return R.success(goods);
    }


}
